
from decimal import Decimal
from typing import Any, List

from .field_base import Field
from .validator import MustDecimal, Validate


def ensure_decimal(val: str, decimals: int = 2):
    '''转换为Decimal'''
    return Decimal(str(val)).quantize(Decimal(f'{0:.{decimals}f}'))


class Str(Field):

    def output(self):
        if self.value is None:
            return self.value
        return str(self.value)


class Int(Field):

    def output(self) -> int:
        if self.value is None:
            return self.value
        return int(self.value)


class Number(Field):

    def __init__(self,
                 required: bool = False,
                 json_key: str = '',
                 default: Any = None,
                 protected: bool = False,
                 decimals: int = 2,
                 minimum: Decimal = None,
                 maxmum: Decimal = None,
                 validators: List[Validate] = None, desc: str = '') -> None:
        super().__init__(required, json_key, default, protected, validators, desc)
        self.decimals = decimals
        self.validators.append(MustDecimal(minimum=minimum, maxmum=maxmum))

    def output(self) -> Decimal:
        if self.value is None:
            return ensure_decimal(0)
        return ensure_decimal(val=self.value, decimals=self.decimals)



class Bool(Field):

    def output(self):
        return bool(self.value)


if __name__ == '__main__':
    n = Number(decimals=3)
    assert n.output(2.353535) == Decimal('2.354'), n.output(2.353535)
    n = Number(decimals=0)
    assert n.output(2.353535) == Decimal('2'), n.output(2.353535)
